package com.wandian.view.stage
{
	import com.wandian.ApplicationFacade;
	import com.wandian.controller.CLZNoticeName;
	import com.wandian.controller.RoleController;
	import com.wandian.core.LoaderManager;
	import com.wandian.data.DataManager;
	import com.wandian.data.GameData;
	import com.wandian.util.ConcurrentQueue;

	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import flash.utils.Dictionary;

	import flashx.textLayout.elements.BreakElement;

	import ghostcat.operation.DelayOper;
	import ghostcat.operation.FunctionOper;
	import ghostcat.util.easing.TweenUtil;

	/**
	 * loading类
	 * @author leo
	 *
	 */
	public class StageLoading extends Sprite
	{
		/**
		 * 是否点击了创建角色界面的开始游戏按钮
		 */
		public var clickStart:Boolean;
		/**
		 * 大loading界面
		 */
		private var bigLoading:MovieClip;

		/**
		 * 配置文件xml
		 */
		private var configXML:XML;
		/**
		 * 进度条
		 */
		private var mcLoading:MovieClip;
		/**
		 * 人物
		 */
		private var mcMan:MovieClip;
		/**
		 * 提示
		 */
		private var txtMsg:TextField;
		/**
		 *  是否全部加载完成
		 */
		private var isLoadingComplete:Boolean;
		/**
		 * 登录ui传过来的 玩家信息
		 */
		private var playerData:Array;

		public function StageLoading()
		{
			super();
			loadConfig();

		}

		/**
		 * 设置进度条的百分比
		 * @param value
		 *
		 */
		public function setPercent(value:int):void
		{
			var str:String=value.toString();
			var ary:Array=str.split("");
			var num:int=0;
			if (ary.length == 1)
			{
				num=int(ary[0]);
				num=num > 0 ? num : 10;
				this.mcLoading.num0.gotoAndStop(11);
				this.mcLoading.num1.gotoAndStop(11);
				this.mcLoading.num2.gotoAndStop(num);
			}
			else if (ary.length == 2)
			{
				this.mcLoading.num0.gotoAndStop(11);
				num=int(ary[0]);
				num=num > 0 ? num : 10;
				this.mcLoading.num1.gotoAndStop(num);
				num=int(ary[1]);
				num=num > 0 ? num : 10;
				this.mcLoading.num2.gotoAndStop(num);
			}
			else if (ary.length == 3)
			{
				num=int(ary[0]);
				num=num > 0 ? num : 10;
				(this.mcLoading.num0 as MovieClip).gotoAndStop(num);
				num=int(ary[1]);
				num=num > 0 ? num : 10;
				this.mcLoading.num1.gotoAndStop(num);
				num=int(ary[2]);
				num=num > 0 ? num : 10;
				this.mcLoading.num2.gotoAndStop(num);
			}

			var w:int=stage.stageWidth;
			TweenUtil.removeAllTween(true);
			TweenUtil.to(this.mcMan, 500, {x: int(value / 100 * w)});

			value=value < 1 ? 1 : value > 100 ? 100 : value;
			if (mcLoading.currentFrame > value)
				return;
			this.mcLoading.gotoAndStop(value);

		}

		/**
		 * 加载完成
		 *
		 */
		public function loadingComplete():void
		{
			trace("StageLoading.loadingComplete()");

			TweenUtil.removeTween(this.mcMan, false);

			TweenUtil.to(this, 500, {x: /*this.stage.stagewidth + 100*/ 0}).onComplete=tweenComplete;
			this.isLoadingComplete=true;

//			tweenComplete();
		}

		public function destroy():void
		{
			this.clickStart=false;
		}

		/**
		 * 显示加载界面，需要传玩家创建角色时的信息
		 * @param playerData
		 *   0     1     2
		 *  名字      性别     职业
		 *
		 * //1为男性  2为女性
		 * //1猛将       2刺客      3谋士
		 */
		public function show(playerData:Array):void
		{
			this.visible=true;
			this.playerData=playerData;

			if (this.isLoadingComplete && this.clickStart)
			{
				TweenUtil.to(this, 1000, {x: 0}).onComplete=tweenComplete;
			}

		}

		public function hide():void
		{
			this.visible=false;
		}

		private function tweenComplete():void
		{
//			if (!clickStart)
//				return;
			TweenUtil.removeAllTween(false);
			if (this.playerData)
			{
				RoleController.I.playerData.roleName=this.playerData[0];
				RoleController.I.playerData.sex=this.playerData[1];
			}
			/*var stageGame:StageGame=new StageGame();
			Texas.I.setStage(stageGame);*/
			//通知加载完毕
			ApplicationFacade.getInstance().sendNotification(CLZNoticeName.APPLICATIONMEDIATOR_LOAD_SWF_COMPLETE);
		}

		/**
		 * 加载游戏配置文件
		 *
		 */
		private function loadConfig():void
		{
			var url:String=GameData.configXML;
			var urlLoader:URLLoader=new URLLoader();
			urlLoader.addEventListener(Event.COMPLETE, completeHandler);
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			urlLoader.load(new URLRequest(url));
			if (Texas.I)
			{
//				var smallLoading:MovieClip=Texas.I.smallLoading;
			}
//			if (smallLoading && smallLoading.parent)
//			{
//				smallLoading.visible=true;
//			}
		}

		/**
		 * 加载游戏配置文件完成
		 * @param event
		 *
		 */
		private function completeHandler(event:Event):void
		{
			var urlLoader:URLLoader=event.target as URLLoader;
			this.configXML=new XML(urlLoader.data);
			GameData.bigLoadingURL=this.configXML.sourceURL.@bigLoadingURL;
			GameData.mapSource=this.configXML.sourceURL.@mapSource;
			GameData.uiDir=this.configXML.sourceURL.@uiSource;
			destroyAddEvent(event);

			var url:String=GameData.bigLoadingURL;
			var loader:Loader=new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onBigLoading);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onBigLoadingErr);
			loader.load(new URLRequest(url));
		}

		/**
		 * 加载大loading界面完成
		 * @param event
		 *
		 */
		private function onBigLoading(event:Event):void
		{
			this.bigLoading=(event.target as LoaderInfo).content as MovieClip;
			this.addChild(this.bigLoading);
			this.mcLoading=this.bigLoading.stageLoading.mcLoading;
			this.mcLoading.num0.gotoAndStop(11); //第11帧为不显示该数字
			this.mcLoading.num1.gotoAndStop(11);
			this.mcLoading.num2.gotoAndStop(10); //第10帧为数字0
			this.mcLoading.gotoAndStop(1);
			this.mcMan=this.bigLoading.stageLoading.mcMan;
			this.mcMan.gotoAndPlay(1);
			this.txtMsg=this.bigLoading.stageLoading.txtMsg;

			destroyLoaderAddEvent(event);
			//加载ui
			loadGameUI();
			//加载文本配置
			loadTxtConfig();

//			var smallLoading:MovieClip=Texas.I.smallLoading;
//			if (smallLoading && smallLoading.parent)
//			{
//				smallLoading.parent.removeChild(smallLoading);
//			}

			this.configXML=null;
		}

		/**
		 * 加载UI
		 *
		 */
		private function loadGameUI():void
		{
			if (this.configXML.gameUI)
			{
				var urlAry:Array=[];
				for each (var item:* in this.configXML.gameUI.item)
				{
					urlAry.push(item.@source);
				}
			}
			else
			{
				trace("at StageLoading loadGameUI xml is null");
			}

			if (urlAry.length > 0)
			{
				var concurrentQueue:ConcurrentQueue=new ConcurrentQueue(urlAry, this);
			}
		}

		/**
		 * 加载文本配置（暂时用于任务）
		 */
		private function loadTxtConfig():void
		{
			if (this.configXML)
			{
				if (this.configXML.txtConfig)
				{
					var str:String=this.configXML.txtConfig.@txt;
					var dir:String=this.configXML.txtConfig.@source;
					var arr:Array=str.split(",");
					var result:Array=[];
					for (var i:int=0; i < arr.length; i++)
					{
						var url:String=dir + arr[i] + ".txt";
						result.push(url);
					}

					if (result.length > 0)
					{
						LoaderManager.instance.loadTxts(result, loadTxtRhand, loadTxtFhand);
					}
				}
			}
		}

		private function loadTxtRhand():void
		{
			trace("加载文本配置完成");

			var dict:Dictionary=LoaderManager.instance.txtDict;
			for (var key:String in dict)
			{
				switch (key)
				{
					case "level":
						DataManager.I.initLevelList();
						break;
					default:
						break;
				}
			}

		}

		private function loadTxtFhand():void
		{
			trace("加载文本配置失败");
		}

		/**
		 * 加载大loading界面失败
		 * @param event
		 *
		 */
		private function onBigLoadingErr(event:Event):void
		{
			trace("加载大loading出错");
			destroyLoaderAddEvent(event);
		}

		/**
		 * 加载游戏配置文件出错
		 * @param event
		 *
		 */
		private function errorHandler(event:IOErrorEvent):void
		{
			destroyAddEvent(event);
			trace("加载config出错");
		}

		/**
		 * 销毁加载游戏配置文件的urlLoader
		 * @param event
		 *
		 */
		private function destroyAddEvent(event:Event):void
		{
			var urlLoader:URLLoader=event.currentTarget as URLLoader;
			urlLoader.removeEventListener(Event.COMPLETE, completeHandler);
			urlLoader.removeEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			urlLoader=null;
		}

		/**
		 *  销毁加载大loading的Loader
		 * @param event
		 *
		 */
		private function destroyLoaderAddEvent(event:Event):void
		{
			var loader:Loader=(event.target as LoaderInfo).loader;
			loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onBigLoading);
			loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onBigLoadingErr);
			loader.unloadAndStop();
			loader=null;
		}

	}
}
